#!/usr/bin/python
# -*- coding:utf-8 -*-

from __future__ import unicode_literals
from __future__ import with_statement
import sys
import os
import re

reload(sys) 
sys.setdefaultencoding("utf-8")

def sync_reformer_parent_pom():
#     parent_pom_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),"reformer-parent/pom.xml")
    parent_pom_path = os.path.abspath("../version-control-parent/pom.xml")
    if not os.path.exists(parent_pom_path):
        raise Exception("File not found:%s" % parent_pom_path);
    with open(parent_pom_path) as f:
        parent_pom_content = f.read();
    #获取
    matches = re.findall( r'.*<dependencyManagement>(.+)</dependencyManagement>', parent_pom_content, re.S)
    if matches:
        target_dependencies = matches[0];
        commons = """
            <dependency>
                <groupId>com.reformer.commons</groupId>
                <artifactId>reformer-commons</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>"""
        target_dependencies = re.subn("</dependencies>", commons, target_dependencies)
        with open("./pom.xml.template") as f:
            current_pom_content = f.read();
        output_xml = current_pom_content % target_dependencies[0]
#         output_xml = re.subn("<!--replaceable-->", target_dependencies[0], current_pom_content)[0]
#         content = re.subn("<dependencies>.+</dependencies>", target_dependencies, current_pom_content, 1, re.S)[0];
        with open("./pom.xml", "w") as f:
            f.write(output_xml)
    else:
        raise Exception("文件格式错误:%s" % parent_pom_path);
    
if __name__ == '__main__':
    sync_reformer_parent_pom()
